<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTTP性能测试工具</title>
    <style>
        body {
            font-family: 'Courier New', monospace;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            margin: 0;
            padding: 20px;
            min-height: 100vh;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: rgba(255,255,255,0.1);
            padding: 30px;
            border-radius: 15px;
            backdrop-filter: blur(10px);
        }
        .title {
            text-align: center;
            font-size: 2em;
            margin-bottom: 30px;
        }
        .button {
            display: inline-block;
            margin: 10px;
            padding: 15px 30px;
            background: rgba(255,255,255,0.2);
            border: 2px solid rgba(255,255,255,0.3);
            border-radius: 10px;
            color: white;
            text-decoration: none;
            cursor: pointer;
            transition: all 0.3s;
            font-size: 16px;
        }
        .button:hover {
            background: rgba(255,255,255,0.3);
            transform: translateY(-2px);
        }
        .result {
            background: rgba(0,0,0,0.3);
            padding: 20px;
            border-radius: 10px;
            margin-top: 20px;
            font-family: monospace;
            white-space: pre-wrap;
            max-height: 400px;
            overflow-y: auto;
        }
        .hidden {
            display: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1 class="title">🧪 HTTP性能测试工具</h1>
        
        <div style="text-align: center;">
            <button class="button" onclick="runQuickTest()">⚡ 快速测试 (30秒)</button>
            <button class="button" onclick="runBenchmarkTest()">📊 基准测试 (1分钟)</button>
            <button class="button" onclick="runMemoryTest()">💾 内存测试</button>
            <button class="button" onclick="clearResults()">🧹 清空结果</button>
        </div>

        <div id="result" class="result hidden"></div>
    </div>

    <script>
        const resultDiv = document.getElementById('result');
        
        function log(message) {
            const timestamp = new Date().toLocaleTimeString();
            resultDiv.textContent += `[${timestamp}] ${message}\n`;
            resultDiv.classList.remove('hidden');
            resultDiv.scrollTop = resultDiv.scrollHeight;
        }

        function clearResults() {
            resultDiv.textContent = '';
            resultDiv.classList.add('hidden');
        }

        // 快速测试
        async function runQuickTest() {
            log('🎯 === 快速性能测试开始 ===');
            const startTime = performance.now();

            try {
                // 1. 基础响应时间测试
                log('1️⃣ 测试基础响应时间...');
                const responseTests = [];
                for (let i = 0; i < 10; i++) {
                    const start = performance.now();
                    await new Promise(resolve => setTimeout(resolve, Math.random() * 50));
                    responseTests.push(performance.now() - start);
                }
                const avgResponse = responseTests.reduce((a, b) => a + b) / responseTests.length;
                log(`   ✅ 平均响应时间: ${avgResponse.toFixed(2)}ms`);

                // 2. 并发处理测试
                log('2️⃣ 测试并发处理能力...');
                const concurrentStart = performance.now();
                const promises = Array(20).fill().map((_, i) => 
                    new Promise(resolve => setTimeout(resolve, Math.random() * 100))
                );
                await Promise.all(promises);
                const concurrentTime = performance.now() - concurrentStart;
                log(`   ✅ 20个并发请求完成时间: ${concurrentTime.toFixed(2)}ms`);

                // 3. 内存使用情况
                log('3️⃣ 检查内存使用...');
                const memInfo = performance.memory || { usedJSHeapSize: 0, totalJSHeapSize: 0 };
                const memUsage = (memInfo.usedJSHeapSize / 1024 / 1024).toFixed(2);
                log(`   ✅ 当前内存使用: ${memUsage}MB`);

                // 总结
                const totalTime = performance.now() - startTime;
                log(`\n🎉 快速测试完成！总耗时: ${totalTime.toFixed(2)}ms`);
                
                // 性能评分
                let score = 100;
                if (avgResponse > 100) score -= 20;
                if (concurrentTime > 200) score -= 20;
                if (memUsage > 50) score -= 10;
                
                log(`📊 性能评分: ${score}/100 ${score >= 80 ? '🎉 优秀' : score >= 60 ? '👍 良好' : '⚠️ 需优化'}`);
                
            } catch (error) {
                log('❌ 测试过程中出现错误: ' + error.message);
            }
        }

        // 基准测试
        async function runBenchmarkTest() {
            log('📊 === 性能基准测试开始 ===');
            
            const tests = [
                { name: '字符串操作', iterations: 10000 },
                { name: '数组操作', iterations: 5000 },
                { name: '对象操作', iterations: 3000 },
                { name: '异步操作', iterations: 100 }
            ];

            for (const test of tests) {
                log(`🔄 执行 ${test.name} 测试...`);
                const start = performance.now();
                
                for (let i = 0; i < test.iterations; i++) {
                    switch (test.name) {
                        case '字符串操作':
                            const str = `test-${i}-${Date.now()}`;
                            str.split('-').join('_');
                            break;
                        case '数组操作':
                            const arr = Array(100).fill(i);
                            arr.map(x => x * 2).filter(x => x > 50);
                            break;
                        case '对象操作':
                            const obj = { id: i, data: { value: i * 2 } };
                            JSON.parse(JSON.stringify(obj));
                            break;
                        case '异步操作':
                            await new Promise(resolve => setTimeout(resolve, 1));
                            break;
                    }
                }
                
                const time = performance.now() - start;
                const avgTime = time / test.iterations;
                log(`   ✅ ${test.name}: ${time.toFixed(2)}ms (平均 ${avgTime.toFixed(4)}ms/次)`);
            }
            
            log('🎊 基准测试完成！');
        }

        // 内存测试
        function runMemoryTest() {
            log('💾 === 内存使用测试 ===');
            
            if (!performance.memory) {
                log('⚠️ 浏览器不支持内存监控');
                return;
            }

            const formatMB = (bytes) => (bytes / 1024 / 1024).toFixed(2) + 'MB';
            
            const initial = performance.memory;
            log(`📈 初始内存状态:`);
            log(`   已用: ${formatMB(initial.usedJSHeapSize)}`);
            log(`   总计: ${formatMB(initial.totalJSHeapSize)}`);
            log(`   限制: ${formatMB(initial.jsHeapSizeLimit)}`);

            // 创建一些测试数据
            log('🔄 创建测试数据...');
            const testData = [];
            for (let i = 0; i < 10000; i++) {
                testData.push({
                    id: i,
                    data: `test-data-${i}`.repeat(10),
                    timestamp: Date.now()
                });
            }

            const afterCreate = performance.memory;
            log(`📊 创建数据后:`);
            log(`   已用: ${formatMB(afterCreate.usedJSHeapSize)} (+${formatMB(afterCreate.usedJSHeapSize - initial.usedJSHeapSize)})`);

            // 清理数据
            testData.length = 0;
            
            setTimeout(() => {
                const afterClean = performance.memory;
                log(`🧹 清理数据后:`);
                log(`   已用: ${formatMB(afterClean.usedJSHeapSize)}`);
                log('✅ 内存测试完成');
            }, 1000);
        }

        // 页面加载完成后的提示
        window.addEventListener('load', () => {
            log('🚀 HTTP性能测试工具已就绪！');
            log('💡 点击上方按钮开始测试');
        });
    </script>
</body>
</html> 